package com.scm.parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;

import scm.live.jaxb.CMPBean;
import scm.live.jaxb.LIVE;
import scm.live.jaxb.MATCHTBean;

import com.scm.error.SCPException;
import com.scm.property.IPropertyConfig;
import com.scm.property.PropertyConfig;

public class TEXTParserLive implements StatisticLive{
	private Logger log = Logger.getLogger(TEXTParserLive.class);
	
	private String urlString = null;
	
	public TEXTParserLive(){
		IPropertyConfig property = new PropertyConfig();
		urlString =	property.getStringUrlLive();
		
	}

	public LIVE getBeanStatistic() throws SCPException {
		URL url;
		String xml = null;
		try {
			url = new URL(urlString);
			URLConnection yc = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
			String inputLine;
			String buffer = "";
		while ((inputLine =  in.readLine()) != null) {
			inputLine = inputLine.trim();
			buffer = buffer + inputLine;
		}
		
		log.info(buffer);
		
		List<String> list = slitString(buffer , "<div style=\"display:block\"><div class=\"sdHpItem boxShadow\" style=\"display:block\">","<div id=\"footer\" class=\"container_32 footer\">");
		
		for(String sub : list) {
			sub =sub.replaceAll("<div style=\"display:block\"><div class=\"sdHpItem boxShadow\" style=\"display:block\">","[LIVE]<div class=\"sdHpItem boxShadow\" style=\"display:block\">");
			sub =sub.replaceAll("<div id=\"footer\" class=\"container_32 footer\">","[/SQ2][/MATCH][/MATCHS][/COMPETATION][/LIVE]");
			sub =sub.replaceAll("</dd></dl></div></div><div><div class=\"sdHpItem boxShadow\" style=\"display:block\">","[/SQ2][/MATCH][/MATCHS][/COMPETATION][COMPETATION]");
			sub =sub.replaceAll("</dd></dl></div></div><div class=\"sdHpItem boxShadow\" style=\"display:block\">","[/SQ2][/MATCH][/MATCHS][/COMPETATION][COMPETATION]");
			sub =sub.replaceAll("<div class=\"sdHpItem boxShadow\" style=\"display:block\">","[COMPETATION]");
			sub =sub.replaceAll("<div class=\"header\" style=\"display:block\"><h2>","[NAME-COMPETATION]");
			sub =sub.replaceAll("</h2></div>","[/NAME-COMPETATION]");//
			sub =sub.replaceAll("<div class=\"mEl show\">","[MATCHS]");
			sub =sub.replaceAll("mElStatus liveBar","mElStatus");
			sub =sub.replaceAll("mElStatus inp","mElStatusinp");
			sub =sub.replaceAll("<dd class=\"mElStatus\">","[MATCH][STATUS]");
			sub =sub.replaceAll("<dd class=\"mElO1\"","[/STATUS][SQ1]<dd class=\"mElO1\"");
			sub =sub.replaceAll("<dd class=\"mElScore\">","[/SQ1][SCORE]");
			sub =sub.replaceAll("</dd></dl><dl id=\"","</dd></dl>[/SQ2][/MATCH]<dl id=\"");
			sub =sub.replaceAll("<dd class=\"mElO2\"","[/SCORE][SQ2]<dd class=\"mElO2\"");
			sub = deleteTag(sub);
			sub =sub.replaceAll("\\[","<");
			sub =sub.replaceAll("\\]",">");		
//			log.info("->"+sub);
			xml =  sub;
		}

		} catch (MalformedURLException e) {
			throw new SCPException("URL_DWNLOAD_PDF_FAILED",665,"URL Download "+""+" Non valido!");
		} catch (IOException e) {
			throw new SCPException("DWNLOAD_PDF_FAILED",666,"Download Pdf Fallito!");
		}
		return loadObject(xml);
	}
	
	public LIVE loadObject(String xml){
		
		try {
			StringReader reader = new StringReader(xml);
			JAXBContext jaxbContext = JAXBContext.newInstance(LIVE.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			LIVE customer = (LIVE) jaxbUnmarshaller.unmarshal(reader);
			log.info(customer.getCOMPETATION().get(0).getNAMECOMPETATION());
			
			LIVE live = new LIVE();
			
			for(CMPBean cmp :  customer.getCOMPETATION()){
				cmp.setID(String.valueOf(customer.getCOMPETATION().indexOf(cmp)));
				live.getCOMPETATION().add(cmp);
			}
			
			return live;
		    } catch (JAXBException e) {
		    	  	log.error("error:",e);
		    }
		return null;
	}
	
	
	public  List<String> slitString(String ori , String start,String end){
		List<String> sequence = new ArrayList<String>();
		String[] temp_ori = ori.split(start);
			if(temp_ori.length > 1 || ori.startsWith(start)){
			List<String> subSequenceList = new LinkedList<String>(Arrays.asList(temp_ori));
			subSequenceList.remove(0);
			for(String str : subSequenceList){
				String temp_1 = start+str;
				String[] temp_arr = temp_1.split(end);
				if(temp_arr.length > 1 || temp_1.endsWith(end)){
					String definitive = temp_arr[0] + end;
					sequence.add(definitive);
				}
			}
		}
		return sequence;
	}
	
	public String deleteTag(String t1){
		String t3 = t1.replaceAll("<[^>]*>", "\n");
		t3 = t3.replaceAll("\\s+", " ");
		t3 = t3.replaceAll("&nbsp;&ndash;&nbsp;","");
		return t3.trim();
	}

}
